package com.dhy.takeaway.controller;

import com.dhy.takeaway.entity.Good;
import com.dhy.takeaway.entity.Res;
import com.dhy.takeaway.entity.Store;
import com.dhy.takeaway.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
public class GoodsController {

    @Value("${picPath}")
    private String path;

    @Autowired
    private GoodsService goodsService;

    //上传pic
    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file) {
        System.out.println("UPLOAD....");
//        String path = "E:\\picture\\upload";
        File filePath = new File(path);

        if (!filePath.exists() && !filePath.isDirectory()) {
            filePath.mkdir();
        }
        //文件名字全称
        String originalFilename = file.getOriginalFilename();
        //文件类型
        String type = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        //文件名字简称
        String name = originalFilename.substring(0,originalFilename.lastIndexOf("."));
        //新文件名
        String fileName = UUID.randomUUID() + name + "." + type;


        //在指定路径下创建一个文件
        File targetFile = new File(path, fileName);

        //将文件保存到服务器指定的位置
        try{
            file.transferTo(targetFile);
//            return path + "\\" + fileName;
            return fileName;
        }catch (IOException e){
            System.out.println("上传失败");
            return "false";
        }

    }

    //删除pic
    @PostMapping("/delFile")
    public String delFile(@RequestBody Map<String,Object> map){
        System.out.println("delFile...");

        String path = this.path + "\\" + map.get("path").toString();
        File file = new File(path);
        if (file.exists()) {
            if (file.delete()) {
                System.out.println("删除成功！");
                return "200";
            } else {
                return "400";
            }
        }

        return "文件不存在！";
    }

    //使用流将图片输出
    @GetMapping("/getImage/{name}")
    public void getImage(HttpServletResponse response, @PathVariable("name") String name) throws IOException {
        System.out.println("getImage...");

        if(name==null || name=="" || "null".equals(name)){
            return;
        }

        String realPath = path + "\\" + name;
        FileInputStream inputStream = new FileInputStream(realPath);
        int i = inputStream.available();
        // byte数组用于存放图片字节数据
        byte[] buff = new byte[i];
        inputStream.read(buff);
        inputStream.close();
        //设置发送到客户端的响应内容类容
        response.setContentType("application/ipa;charset=utf-8");
        response.setHeader("Content-Disposition", "inline");// filename=pic.png
        OutputStream out = response.getOutputStream();
        out.write(buff);
        out.close();

//        ServletOutputStream outputStream = response.getOutputStream();
//        outputStream.write(Files.readAllBytes(Paths.get(p).resolve(name)));
//        outputStream.flush();
//        outputStream.close();
    }


    // 商品提交
    @PostMapping("/goodAdd")
    public Res goodAdd(@RequestBody Good good){
        Res res = new Res();
        System.out.println(good);

        if (good.getId() != "" && good.getId() != null) {
            if (goodsService.goodEdit(good)) {
                res.setCode("200");
                res.setMessage("更改成功");
            }else{
                res.setCode("400");
                res.setMessage("商品更改失败！");
            }
        }else{
            if(goodsService.goodAdd(good)){
                res.setCode("200");
                res.setMessage("商品添加成功！");
            }else{
                res.setCode("400");
                res.setMessage("商品添加失败！");
            }
        }


        return res;
    }

    //售卖商品List
    @PostMapping("/goodList")
    public List<Good> goodList(@RequestBody Good good){
        return goodsService.goodList(good.getUserId());
    }
    //下架商品List
    @PostMapping("/soldOutList")
    public List<Good> soldOutList(@RequestBody Good good){
        return goodsService.soleOutList(good.getUserId());
    }

    //下架商品
    @PostMapping("/soldOut")
    public Res soldOut(@RequestBody Good good){
        System.out.println(good.getId());
        Res res = new Res();
        if (goodsService.soldOut(good.getId())) {
            res.setCode("200");
            res.setMessage("商品下架成功！");
        } else {
            res.setCode("400");
            res.setMessage("商品下架失败！");
        }
        return res;
    }
    //上架商品
    @PostMapping("/putAway")
    public Res putAway(@RequestBody Good good){
        System.out.println(good.getId());
        Res res = new Res();
        if (goodsService.putAway(good.getId())) {
            res.setCode("200");
            res.setMessage("商品上架成功！");
        } else {
            res.setCode("400");
            res.setMessage("商品上架失败！");
        }
        return res;
    }

    //热销 商品
    @PostMapping("/hotSale")
    public List<Good> hotSale(@RequestBody Good good){
        return goodsService.findHotSale(good.getUserId());
    }

    //必选物品
    @PostMapping("/mustGood")
    public List<Good> mustGood(@RequestBody Good good){
        return goodsService.findMustGood(good.getUserId());
    }
}
